<template>
  <div class="padding">
    <el-card class="box-card">
      <el-form
        :inline="true"
        :model="searchCriteria"
        class="margin-top-sm padding-top"
        size="mini"
        label-width="70px"
      >
        <el-row>
          <el-col :span="22">
            <el-row>
              <el-col :span="6">
                <el-form-item label="shipmentId">
                  <el-input
                    v-model="searchCriteria.shipmentId"
                    placeholder="shipmentId"
                    clearable
                    @keyup.enter.native="searchData(searchCriteria)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="仓库代码">
                  <el-input
                    v-model="searchCriteria.destinationFulfillmentCenterId"
                    placeholder="仓库代码"
                    clearable
                    @keyup.enter.native="searchData(searchCriteria)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="国家">
                  <el-select
                    v-model="searchCriteria.shipToCountryCode"
                    filterable
                    clearable
                    placeholder="国家"
                  >
                    <el-option
                      v-for="(v, i) in countryCodeSource"
                      :key="i"
                      :label="v"
                      :value="i"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="货件状态">
                  <el-select
                    v-model="searchCriteria.status"
                    placeholder="请选择货件状态"
                    clearable
                  >
                    <el-option
                      v-for="(item, value) in planStatusSource"
                      :key="value"
                      :label="item"
                      :value="parseInt(value)"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="2">
            <el-button
              type="primary"
              size="mini"
              @click="searchData(searchCriteria)"
            >
              查询
            </el-button>
            <el-button type="primary" size="mini" @click="onReset">
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="margin-top">
      <el-row>
        <el-col :span="20">
          <el-pagination
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100, 200]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="parseInt(total)"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="mini" @click="batchCreateFbaOrder">
            FBA批量下单
          </el-button>
        </el-col>
      </el-row>

      <el-table
        ref="multipleTable"
        size="mini"
        border
        :data="
          tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)
        "
        style="width: 100%"
        class="margin-top"
        tooltip-effect="light"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="货件名称"
          align="center"
          prop="shipmentName"
          width="200"
        />

        <el-table-column
          label="shipmentId"
          align="center"
          prop="shipmentId"
          width="150"
        />

        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            {{ planStatusSource[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column label="国家" align="center" prop="shipToCountryCode" />
        <!--鼠标聚焦仓库的具体地址 shipToName(名称) shipToStateOrProvinceCode(州/省)  shipToCity(城市)  shipToDistrictOrCounty(区县)  shipToAddressLine1(地址一) shipToAddressLine2(地址二) shipToPostalCode(邮编)-->
        <el-table-column
          label="仓库"
          align="center"
          prop="destinationFulfillmentCenterId"
        >
          <template slot-scope="scope">
            <el-popover placement="bottom" trigger="hover">
              <el-link
                slot="reference"
                :underline="false"
                class="text-sm"
                style="color: #409eff"
              >
                {{ scope.row.destinationFulfillmentCenterId }}
              </el-link>
              <div class="text-sm">
                <p>名称：{{ scope.row.shipToName }}</p>
                <p>州/省：{{ scope.row.shipToStateOrProvinceCode }}</p>
                <p>城市：{{ scope.row.shipToCity }}</p>
                <p>区县：{{ scope.row.shipToDistrictOrCounty }}</p>
                <p>地址一：{{ scope.row.shipToAddressLine1 }}</p>
                <p>地址二：{{ scope.row.shipToAddressLine2 }}</p>
                <p>邮编：{{ scope.row.shipToPostalCode }}</p>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <!--鼠标点击展示SKU详细信息-->
        <el-table-column
          prop="inboundShipmentPlanItems"
          label="SKU信息"
          align="center"
        >
          <template slot-scope="scope">
            <el-button class="text-sm" type="text" @click="viewSku(scope.row)">
              SKU信息
            </el-button>
          </template>
        </el-table-column>
        <!--鼠标点击展示装箱单详细信息-->
        <el-table-column prop="packLists" label="装箱单" align="center">
          <template slot-scope="scope">
            <el-button
              class="text-sm"
              type="text"
              @click="viewPackLists(scope.row)"
            >
              装箱单
            </el-button>
          </template>
        </el-table-column>
        <!--http://www.tofba.com:8080/+localLabelUrl  文件服务器地址-->
        <el-table-column prop="localLabelUrl" label="面单" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.localLabelUrl"
              type="text"
              class="text-sm"
              @click="viewLocalLabelUrl(scope.row)"
            >
              点击查看面单
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="waybillNo" label="运单号" align="center" />
        <el-table-column
          prop="cdate"
          label="创建时间"
          align="center"
          width="130"
        />
        <el-table-column
          prop="shopName"
          label="店铺名称"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column prop="sysRemark" label="日志" align="center">
          <template slot-scope="scope">
            <el-popover placement="bottom" trigger="hover">
              <el-link
                slot="reference"
                :underline="false"
                class="text-sm"
                style="color: #409eff"
              >
                日志
              </el-link>
              <div class="text-sm" v-html="scope.row.sysRemark">
                <!-- {{ scope.row.sysRemark }} -->
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <!--操作-->
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <!--操作：确认计划请求：manualCreateInboundShipment，参数：id，触发条件：状态为：20(待确认发货计划)-->
            <el-tooltip
              v-if="scope.row.status === 20"
              class="item margin-left-xs text-green"
              effect="dark"
              content="确认计划"
              placement="top"
            >
              <i
                class="el-icon-circle-check operation-icon pointer text-xl"
                @click="colConfirmPlan(scope.row)"
              />
            </el-tooltip>
            <!--操作：填写装箱单[新增&修改]请求：toCreatePackList-页面加载，createPackList-保存操作 参数：id，触发条件：状态为：30(待提交装箱单)-->
            <el-tooltip
              v-if="scope.row.status === 30"
              class="item margin-left-xs text-blue"
              effect="dark"
              content="填写装箱单"
              placement="top"
            >
              <i
                class="el-icon-edit-outline operation-icon pointer text-xl"
                @click="colCreatePackList(scope.row)"
              />
            </el-tooltip>
            <!--操作：确认装箱单请求：confirmPackList，参数：id，触发条件：状态为：30(待提交装箱单) && 装箱单状态为草稿状态(packListStatus:0)-->
            <el-tooltip
              v-if="scope.row.status === 30 && scope.row.packListStatus === 0"
              class="item margin-left-xs text-green"
              effect="dark"
              content="确认装箱单"
              placement="top"
            >
              <i
                class="el-icon-document-checked operation-icon pointer text-xl"
                @click="colConfirmPackList(scope.row)"
              />
            </el-tooltip>
            <!--操作：手动提交补料 请求：manualSubmitFeed，参数：id，触发条件：状态为：40(待提交补料) && 装箱单状态为确认(packListStatus:1)-->
            <el-tooltip
              v-if="
                (scope.row.status === 40 || scope.row.status === 45) &&
                  scope.row.packListStatus === 1
              "
              class="item margin-left-xs text-blue"
              effect="dark"
              content="提交补料"
              placement="top"
            >
              <i
                class="el-icon-finished operation-icon pointer text-xl"
                @click="colManualSubmitFeed(scope.row)"
              />
            </el-tooltip>
            <!--操作：查看补料结果 请求：manualGetFeed，参数：id，触发条件：feedDocumentId && feedId 值不为空-->
            <el-tooltip
              v-if="scope.row.feedDocumentId && scope.row.feedId"
              class="item margin-left-xs text-orange"
              effect="dark"
              content="查看补料结果"
              placement="top"
            >
              <i
                class="el-icon-document operation-icon pointer text-xl"
                @click="colManualGetFeed(scope.row)"
              />
            </el-tooltip>
            <!--操作：上传承运人信息 请求：manualPutTransportDetails 参数：id，触发条件：状态为：50(待上传承运人信息) -->
            <el-tooltip
              v-if="scope.row.status === 50"
              class="item margin-left-xs text-blue"
              effect="dark"
              content="上传承运人信息"
              placement="top"
            >
              <i
                class="el-icon-upload2 operation-icon pointer text-xl"
                @click="colManualPutTransportDetails(scope.row)"
              />
            </el-tooltip>
            <!--操作：查看承运人信息getTransportDetails参数：id，触发条件：状态为：60(待获取面单) -->
            <el-tooltip
              v-if="scope.row.status === 60"
              class="item margin-left-xs text-blue"
              effect="dark"
              content="查看承运人信息"
              placement="top"
            >
              <i
                class="el-icon-tickets operation-icon pointer text-xl"
                @click="colGetTransportDetails(scope.row)"
              />
            </el-tooltip>
            <!--操作：获取面单 manualGetLabels 参数：id，触发条件：状态为：60(待获取面单) -->
            <el-tooltip
              v-if="scope.row.status === 60"
              class="item margin-left-xs text-blue"
              effect="dark"
              content="获取面单"
              placement="top"
            >
              <i
                class="el-icon-document-remove operation-icon pointer text-xl"
                @click="colManualGetLabels(scope.row)"
              />
            </el-tooltip>
            <!-- 操作：确认发货 shipped  状态为70 -->
            <el-tooltip
              v-if="scope.row.status === 80"
              class="item margin-left-xs text-green"
              effect="dark"
              content="确认发货"
              placement="top"
            >
              <i
                class="el-icon-success operation-icon pointer text-xl"
                @click="colShipped(scope.row)"
              />
            </el-tooltip>

            <!-- 操作：取消发货  voidTransportDetails  状态为50或者60 -->
            <el-tooltip
              v-if="scope.row.status === 80"
              class="item margin-left-xs text-red"
              effect="dark"
              content="取消发货"
              placement="top"
            >
              <i
                class="el-icon-circle-close operation-icon pointer text-xl"
                @click="cancelShipment(scope.row)"
              />
            </el-tooltip>

            <!--操作：物流服务商下单 createFbaOrder 参数：List<shipmentId>, 触发条件：状态为：70(待物流服务商下单) -->
            <el-tooltip
              v-if="scope.row.status === 70 && !scope.row.waybillNo"
              class="item margin-left-xs text-blue"
              effect="dark"
              content="FBA下单"
              placement="top"
            >
              <i
                class="el-icon-s-order operation-icon pointer text-xl"
                @click="showCreateOrderType(scope.row)"
              />
            </el-tooltip>
            <!--批量操作：物流服务商下单 createFbaOrder 参数：List<shipmentId>, 触发条件：状态为：大于40 && waybillNo为空 选择多个shipmentId目的仓库一致的一起下单 -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 查看sku信息 -->
    <el-dialog title="SKU信息" :visible.sync="viewSkuDialog">
      <el-table :data="viewSkuData" class="text-sm">
        <el-table-column label="SKU" prop="sellerSKU" width="140" />
        <el-table-column label="ASIN" prop="asin" width="140" />
        <el-table-column label="物品状况" prop="condition" width="140" />
        <el-table-column
          label="FNSKU"
          prop="fulfillmentNetworkSKU"
          width="140"
        />
        <el-table-column label="数量" prop="quantity" />
        <el-table-column label="每套个数" prop="quantityInCase" />
      </el-table>
    </el-dialog>
    <!-- 查看装箱单 -->
    <el-dialog title="装箱单" :visible.sync="viewPackList">
      <el-table :data="viewPackListData" class="text-sm">
        <el-table-column label="箱号" prop="cartonId" width="150" />
        <el-table-column label="单箱毛重(KG)" prop="weight" />
        <el-table-column label="长(CM)" prop="length" />
        <el-table-column label="宽(CM)" prop="width" />
        <el-table-column label="高(CM)" prop="height" />
      </el-table>
    </el-dialog>
    <!-- 下单方式 -->
    <el-dialog title="选择下单方式" :visible.sync="selectOrderType" width="26%">
      <div class="text-center">
        <el-radio-group
          v-model="createType"
          size="medium"
          @change="colCreateFbaOrder"
        >
          <el-radio label="orderToSeaFreight">海运</el-radio>
          <el-radio label="OrderToAirFreight">空运</el-radio>
          <el-radio label="OrderToExpressDelivery">快递</el-radio>
        </el-radio-group>
      </div>
    </el-dialog>

    <!-- 填写装箱单 -->
    <el-dialog title="装箱单" :visible.sync="editPackList" width="60%">
      <el-form :model="packListForm" :inline="true">
        <el-row>
          <el-col :span="6">
            <el-form-item prop="rule">
              <div slot="label">箱号规则：</div>
              <el-select
                v-model="packListForm.rule"
                placeholder="请选择"
                size="mini"
                @change="
                  val => {
                    changeRule(val)
                  }
                "
              >
                <el-option
                  v-for="(optionItem, optionIndex) in boxRule"
                  :key="optionIndex"
                  :label="optionItem"
                  :value="optionItem"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="startBoxNo">
              <div slot="label">起始箱号：</div>
              <el-tooltip class="item" effect="light" placement="top-end">
                <div slot="content">
                  起始箱号为1，不填写结束箱号，则是填写1箱的数据。
                  <br>起始箱号为1，结束箱号为1，则是填写1箱的数据。
                  <br>起始箱号为1，结束箱号为2，则是填写2箱的数据。
                </div>
                <el-input
                  v-model="packListForm.startBoxNo"
                  style="width: 150px"
                  type="number"
                  size="mini"
                  placeholder="请填写起始箱号"
                  maxlength="4"
                  max="9999"
                  min="1"
                  @input="
                    packListForm.startBoxNo.length > 4
                      ? (packListForm.startBoxNo = packListForm.startBoxNo.slice(
                        0,
                        4
                      ))
                      : packListForm.startBoxNo
                  "
                />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="endBoxNo">
              <div slot="label">结束箱号：</div>
              <el-input
                v-model="packListForm.endBoxNo"
                style="width: 150px"
                type="number"
                size="mini"
                maxlength="4"
                max="9999"
                min="0"
                placeholder="请填写结束箱号"
                @input="
                  packListForm.startBoxNo.length > 4
                    ? (packListForm.startBoxNo = packListForm.startBoxNo.slice(
                      0,
                      4
                    ))
                    : packListForm.startBoxNo
                "
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" size="mini" @click.native="selectSKUdata">
              选择SKU
            </el-button>
          </el-col>
        </el-row>
      </el-form>

      <el-table
        v-if="packLists && packLists.length > 0"
        ref="multipleTable"
        :header-cell-style="{ background: '#f5f9fc' }"
        size="mini"
        border
        :data="packLists"
        style="width: 100%"
        class="margin-top"
        tooltip-effect="light"
        @selection-change="handleSelectionChange($event, index)"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="箱号"
          align="center"
          prop="cartonId"
          width="200"
        />
        <el-table-column prop="weight" label="单箱毛重(kg)" align="center" />
        <el-table-column
          prop="LWH"
          label="长×宽×高(cm)"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.length }}</span>
            <span v-if="scope.row.length">X</span>
            <span>{{ scope.row.width }}</span>
            <span v-if="scope.row.width">X</span>
            <span>{{ scope.row.height }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="skus"
          label="SKU"
          align="center"
          min-width="400"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.skus[0].sku }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="skuNum"
          label="个数"
          align="center"
          min-width="50"
        /> -->
        <el-table-column label="" width="50" align="center">
          <template slot-scope="scope">
            <i
              class="el-icon-delete padding-lr-sm pointer"
              @click="handleDelete(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="编辑" width="60" align="center">
          <template slot-scope="scope">
            <i
              class="el-icon-edit padding-lr-sm pointer"
              @click="handleEdit(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editPackList = false">取 消</el-button>
        <el-button type="primary" @click="saveCreatePackList(1)">
          确 认
        </el-button>
      </div>
    </el-dialog>

    <!-- 选择sku -->
    <el-dialog :visible.sync="selectSKU" :title="dialogTitle" width="60%">
      <div class="margin-top">
        <!-- <p class="text-center">
          {{ dialogHead }}
        </p> -->

        <el-table
          :data="selectTable"
          max-height="500"
          tooltip-effect="light"
          class="text-sm"
        >
          <el-table-column type="index" label="序号" width="60" />

          <el-table-column property="sellerSKU" label="SKU" width="300" />

          <el-table-column property="quantity" label="总个数" />
          <!-- <el-table-column label="剩余个数">
            <template slot-scope="scope">
              {{ updateRemainingNum(scope, showIndex) }}
            </template>
          </el-table-column> -->
          <el-table-column
            :label="dialogTitle === '选择SKU' ? '装入每箱数量' : '装入该箱数量'"
            property="quantityInCase"
          >
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.quantityInCase"
                size="mini"
                type="number"
                min="0"
                placeholder="请填写数量"
                @input="checkNum(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
        <el-form
          class="margin-top"
          :model="dialogInfo"
          :rules="dialogRule"
          size="mini"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label-width="110px" prop="weight">
                <div slot="label">单箱毛重(KG):</div>

                <el-input v-model.trim="dialogInfo.weight" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="16" class="flex">
              <div
                class="
                  flex-sub
                  form-input-length
                  text-right
                  padding-right-sm
                  text-sm
                "
              >
                <span>单箱长X宽X高(cm):</span>
              </div>

              <el-row :gutter="10" class="flex-twice">
                <el-col :span="7">
                  <el-form-item prop="length" label-width="0">
                    <el-input
                      v-model.trim="dialogInfo.length"
                      placeholder="长"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="1" class="form-input-length">X</el-col>
                <el-col :span="7">
                  <el-form-item prop="width" label-width="0">
                    <el-input
                      v-model.trim="dialogInfo.width"
                      placeholder="宽"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="1" class="form-input-length">X</el-col>
                <el-col :span="7">
                  <el-form-item prop="height" label-width="0">
                    <el-input
                      v-model.trim="dialogInfo.height"
                      placeholder="高"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectSKU = false">取 消</el-button>
        <el-button
          v-if="dialogTitle === '选择SKU'"
          @click="saveCreatePackList(0)"
        >
          草 稿
        </el-button>
        <el-button
          v-if="dialogTitle === '选择SKU'"
          type="primary"
          @click="saveCreatePackList(1)"
        >
          确认装箱单
        </el-button>
        <el-button v-else type="primary" @click="onSave"> 保 存 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  planList,
  planFindById,
  planCount,
  planInit,
  toCreatePackList,
  createPackList,
  manualCreateInboundShipment,
  manualGetFeed,
  manualPutTransportDetails,
  getTransportDetails,
  confirmPackList,
  manualSubmitFeed,
  manualGetLabels,
  createFbaOrder,
  shipped,
  voidTransportDetails
} from '@/api/amazon'
import { clone } from '@/utils/clone'
import globalData from '@/utils/config'

export default {
  data() {
    return {
      currentPage: 1,
      startBoxNo: 1,
      endBoxNo: 1,
      total: 0,
      pagesize: 10,
      rule: '',
      id: '',
      dialogTitle: '选择SKU',
      shipmentId: '',
      selectOrderType: false,
      editPackList: false,
      selectSKU: false,
      viewPackList: false,
      viewSkuDialog: false,
      cloneData: [],
      dialogInfo: {
        length: '',
        width: '',
        height: '',
        weight: ''
      },
      shipmentIdList: [],
      createType: '',
      multipleSelection: [],
      dialogRule: {
        length: [
          { required: false, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: '须为数字,可留3位小数'
          }
        ],
        width: [
          { required: false, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: '须为数字,可留3位小数'
          }
        ],
        height: [
          { required: false, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: '须为数字,可留3位小数'
          }
        ],
        grossWeight: [
          { required: false, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: '须为数字,可留3位小数'
          }
        ]
      },
      packLists: [
        // {
        //   shipmentId: 'FBA16D5W6C2P',
        //   cartonId: 'FBA16D5W6C2PU001',
        //   length: 24.5,
        //   width: 23.5,
        //   height: 20.5,
        //   weight: 10.5,
        //   skus: [
        //     {
        //       sku: '7X-AOK1-BDEU',
        //       quantityShipped: 10
        //     }
        //   ],
        //   cdate: null
        // }
      ],
      packListForm: {
        startBoxNo: ''
      },
      saveIndex: '',
      searchCriteria: {},
      planStatusSource: {},
      countryCodeSource: {},
      boxRule: {},
      packListsData: [],
      viewPackListData: [],
      viewSkuData: [],
      selectTable: [],
      tableData: [],
      flag: false
    }
  },
  computed: {
    ...mapGetters(['publicData'])
  },
  mounted() {
    this.init()
    this.planCount()
  },
  methods: {
    // 页面初始化
    async init() {
      this.$store.dispatch('app/toggleDialog', true)
      const res = await planInit({}) // ==> init
      if (res.code === 200) {
        this.countryCodeSource = res.data.countryCodeSource // 国家下拉
        this.planStatusSource = res.data.planStatusSource // 发货状态
      } else {
        this.$message.error(res.message || '页面初始化失败，请刷新重试')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    // 总数量
    async planCount() {
      this.$store.dispatch('app/toggleDialog', true)
      const res = await planCount({})
      this.$store.dispatch('app/toggleDialog', false)
      this.total = res
      this.planList()
    },
    async planList() {
      this.$store.dispatch('app/toggleDialog', true)
      const res = await planList({ size: this.total })
      this.$store.dispatch('app/toggleDialog', false)
      this.tableData = res
      this.cloneData = res
    },
    searchData(val) {
      // this.$store.dispatch('app/toggleDialog', true)
      // console.log(11, val)
      if (val.shipmentId) {
        const filterData = this.cloneData.filter(
          x => x.shipmentId === val.shipmentId
        )
        this.tableData = filterData
      } else if (val.destinationFulfillmentCenterId) {
        const filterData = this.cloneData.filter(
          x =>
            x.destinationFulfillmentCenterId ===
            val.destinationFulfillmentCenterId
        )
        this.tableData = filterData
      } else if (val.shipToCountryCode) {
        const filterData = this.cloneData.filter(
          x => x.shipToCountryCode === val.shipToCountryCode
        )
        this.tableData = filterData
      } else if (val.status) {
        const filterData = this.cloneData.filter(x => x.status === val.status)
        this.tableData = filterData
      }
      if (val.shipToCountryCode && val.status) {
        const filterData = this.cloneData.filter(
          x =>
            x.status === val.status &&
            x.shipToCountryCode === val.shipToCountryCode
        )
        this.tableData = filterData
      }
      if (val.shipToCountryCode && val.destinationFulfillmentCenterId) {
        const filterData = this.cloneData.filter(
          x =>
            x.destinationFulfillmentCenterId ===
              val.destinationFulfillmentCenterId &&
            x.shipToCountryCode === val.shipToCountryCode
        )
        this.tableData = filterData
      }
      if (val.status && val.destinationFulfillmentCenterId) {
        const filterData = this.cloneData.filter(
          x =>
            x.status === val.status &&
            x.destinationFulfillmentCenterId ===
              val.destinationFulfillmentCenterId
        )
        this.tableData = filterData
      }
      console.log(' this.tableData: ', this.tableData)
    },
    selectSKUdata() {
      if (
        this.packListForm.startBoxNo &&
        this.packListForm.endBoxNo &&
        this.packListForm.rule
      ) {
        this.selectSKU = true
      } else {
        this.$message.warning('箱号规则，起始箱号，结束箱号不能为空')
      }
    },
    changeRule(val) {
      // '当前箱号序号大于999,不能使用U001箱号规则,请重选箱号规则'
      const data = this.packLists
      console.log(val)
      if (
        val === 'U001' &&
        data.length > 0 &&
        data[data.length - 1].cartonId.slice(3) > 999
      ) {
        this.$alert(
          '当前箱号序号大于999,不能使用U001箱号规则,请重选箱号规则',
          'U001箱号规则',
          {
            confirmButtonText: '确定',
            callback: action => {
              rule = oldRule
            }
          }
        )
      }
    },
    handleSizeChange(val) {
      this.pagesize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    handleDelete(rowIndex, row) {
      this.packLists.splice(rowIndex, 1)
    },
    handleEdit(rowIndex, row) {
      this.dialogTitle = '编辑箱单SKU个数'
      this.selectSKU = true
      this.saveIndex = rowIndex
      this.dialogInfo.weight = row.weight
      this.dialogInfo.length = row.length
      this.dialogInfo.height = row.height
      this.dialogInfo.width = row.width
      for (const c of row.skus) {
        this.selectTable[0].quantityInCase = c.quantityShipped
      }
    },
    checkNum(scope) {
      if (scope.quantityInCase > scope.quantity) {
        return this.$message.error('装入该箱SKU个数超过总个数')
      }
      if (this.packLists.length * scope.quantityInCase > scope.quantity) {
        this.$message.error('装入该箱SKU个数超过总个数')
        this.flag = false
      } else {
        this.flag = true
      }
    },
    // 查看sku信息
    viewSku(val) {
      this.viewSkuDialog = true
      this.viewSkuData = []
      if (
        val.inboundShipmentPlanItems &&
        val.inboundShipmentPlanItems.length > 0
      ) {
        this.viewSkuData = val.inboundShipmentPlanItems
      }
    },
    // 查看装箱单
    viewPackLists(val) {
      this.viewPackList = true
      this.viewPackListData = []
      if (val.packLists && val.packLists.length > 0) {
        this.viewPackListData = val.packLists
      }
    },
    // 查看面单
    viewLocalLabelUrl(val) {
      window.open(globalData.fileUrl + val.localLabelUrl)
    },
    // 确认计划
    async colConfirmPlan(val) {
      this.$store.dispatch('app/toggleDialog', true)
      const res = await manualCreateInboundShipment({ id: val.id })
      if (res.code === 200) {
        this.$message.success(res.message || '操作成功')
        this.planList()
      } else {
        this.$message.error(res.message || '操作失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    // 填写装箱单
    async colCreatePackList(val) {
      this.id = val.id
      this.shipmentId = val.shipmentId
      const res = await toCreatePackList({ id: val.id })
      console.log(res)
      if (res.code === 200) {
        this.editPackList = true
        this.packLists = res.data.amazonInboundShipmentPlan.packLists
        this.boxRule = res.data.boxRuleSource
        this.selectTable =
          res.data.amazonInboundShipmentPlan.inboundShipmentPlanItems
      } else {
        this.$message.error(res.message || '加载箱单页面失败')
      }
    },
    onSave() {
      if (this.flag) {
        this.packLists[this.saveIndex].weight = Number(this.dialogInfo.weight)
        this.packLists[this.saveIndex].length = Number(this.dialogInfo.length)
        this.packLists[this.saveIndex].width = Number(this.dialogInfo.width)
        this.packLists[this.saveIndex].height = Number(this.dialogInfo.height)

        for (const i of this.packLists[this.saveIndex].skus) {
          for (const k of this.selectTable) {
            i.quantityShipped = k.quantityInCase
          }
        }
        this.selectSKU = false
      } else {
        this.$message.error('装入该箱SKU个数超过总个数')
      }
    },
    // 保存-装箱单
    async saveCreatePackList(val) {
      let packLists = []
      if (this.packLists && this.packLists.length > 0 && this.flag) {
        packLists = this.packLists
      } else {
        const num =
          this.packListForm.endBoxNo - this.packListForm.startBoxNo + 1
        for (const i of this.selectTable) {
          for (let index = 0; index < num; index++) {
            const boxNum = (
              parseInt(this.packListForm.startBoxNo) + index
            ).toString()
            const ruleStr =
              this.packListForm.rule.slice(
                0,
                this.packListForm.rule.length - boxNum.length
              ) + boxNum
            const cartonId = `${this.shipmentId + ruleStr}`
            const data = {
              shipmentId: this.shipmentId,
              cartonId: cartonId,
              // length: this.shipmentId,
              weight: Number(this.dialogInfo.weight),
              length: Number(this.dialogInfo.length),
              height: Number(this.dialogInfo.height),
              width: Number(this.dialogInfo.width),
              skus: [
                {
                  sku: i.sellerSKU,
                  quantityShipped: i.quantityInCase
                }
              ]
            }
            packLists.push(data)
          }
        }
      }

      this.$store.dispatch('app/toggleDialog', true)
      const res = await createPackList({
        id: this.id,
        packListStatus: val,
        packLists
      })
      console.log(res)
      if (res.code === 200) {
        this.$message.success('保存成功')
        this.planList()
        this.selectSKU = false
        this.editPackList = false
      } else {
        this.$message.error(res.message || '保存失败')
      }

      this.dialogInfo = {
        length: '',
        width: '',
        height: '',
        weight: ''
      }
      this.planList()
      this.$store.dispatch('app/toggleDialog', false)
    },
    // 确认装箱单
    async colConfirmPackList(val) {
      this.$store.dispatch('app/toggleDialog', true)
      const res = await confirmPackList({ id: val.id })
      if (res.code === 200) {
        this.$message.success(res.message || '操作成功')
        this.planList()
      } else {
        this.$message.error(res.message || '操作失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    // 确认发货
    async colShipped(val) {
      this.$store.dispatch('app/toggleDialog', true)
      const res = await shipped({ id: val.id })
      if (res.code === 200) {
        this.$message.success(res.message || '操作成功')
        this.planList()
      } else {
        this.$message.error(res.message || '操作失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    cancelShipment(val) {
      this.$confirm('确认取消发货？')
        .then(_ => {
          this.colVoidTransportDetails(val)
        })
        .catch(_ => {})
    },
    // 取消发货
    async colVoidTransportDetails(val) {
      // console.log('val: ', val)
      this.$store.dispatch('app/toggleDialog', true)
      const res = await voidTransportDetails({ id: val.id })
      if (res.code === 200) {
        this.$message.success(res.message || '操作成功')
        this.planList()
      } else {
        this.$message.error(res.message || '操作失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    // 提交补料
    async colManualSubmitFeed(val) {
      this.$store.dispatch('app/toggleDialog', true)
      const res = await manualSubmitFeed({ id: val.id })
      if (res.code === 200) {
        this.$message.success(res.message || '操作成功')
        this.planList()
      } else {
        this.$message.error(res.message || '操作失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    // 查看补料结果
    async colManualGetFeed(val) {
      this.$store.dispatch('app/toggleDialog', true)
      const res = await manualGetFeed({ id: val.id })
      if (res.code === 200) {
        this.$message.success(res.message || '操作成功')
        this.planList()
      } else {
        this.$message.error(res.message || '操作失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    // 上传承运人信息
    async colManualPutTransportDetails(val) {
      this.$store.dispatch('app/toggleDialog', true)
      const res = await manualPutTransportDetails({ id: val.id })
      if (res.code === 200) {
        this.$message.success(res.message || '操作成功')
        this.planList()
      } else {
        this.$message.error(res.message || '操作失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    // 查看承运人信息
    async colGetTransportDetails(val) {
      this.$store.dispatch('app/toggleDialog', true)
      const res = await getTransportDetails({ id: val.id })
      if (res.code === 200) {
        this.$message.success(res.message || '操作成功')
        this.planList()
      } else {
        this.$message.error(res.message || '操作失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    // 获取面单
    async colManualGetLabels(val) {
      this.$store.dispatch('app/toggleDialog', true)
      const res = await manualGetLabels({ id: val.id })
      if (res.code === 200) {
        this.$message.success(res.message || '操作成功')
        this.planList()
      } else {
        this.$message.error(res.message || '操作失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    showCreateOrderType(val) {
      this.selectOrderType = true
      this.shipmentIdList = val.shipmentId
    },

    // 物流服务商下单
    async colCreateFbaOrder() {
      this.$router.push({
        name: 'CreateOrder',
        params: { shipmentId: this.shipmentIdList, createType: this.createType }
      })
    },
    batchCreateFbaOrder() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择要下单的数据')
        return
      }
      const arr = []
      const key = this.multipleSelection[0].destinationFulfillmentCenterId
      for (const i of this.multipleSelection) {
        if (i.destinationFulfillmentCenterId !== key) {
          this.$message.error('请选择相同仓库的数据下单！')
          return
        }
        arr.push(i.shipmentId)
      }
      this.selectOrderType = true
      this.shipmentIdList = arr
    },
    onReset() {
      this.currentPage = 1
      this.searchCriteria = {
        shipmentId: '',
        destinationFulfillmentCenterId: '',
        shipToCountryCode: '',
        status: ''
      }
      this.planList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>
<style scoped>
.form-input-length {
  line-height: 30px;
}
</style>
